package com.cwj.lab2;

import com.cwj.lab1.myArrayList;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class HFMcode {
    HashMap<Character, myArrayList<Character>> code = null;
    private final String pp = "src/src/com/cwj/lab2/HFM_Data";
/**
 * 编码操作：即对字符串路径的文件进行哈夫曼编码
 * */
    public HashMap<Character, myArrayList<Character>> Encoder(String path) {
        HashMap<Character, Integer> map = Dataprocess(path);
        HFMTree<Character> tree = new HFMTree<>();
        tree.creatTree(HFMTree.Node<Character>::new ,map);
        return code = tree.getCode();
//        HFMTree.HFMTree.Node::new;
    }
/**
 * 数据处理，即统计文件中字符出现的频数
 * 其利用哈希表完成
 * */
    public HashMap<Character, Integer> Dataprocess(String path) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        try (BufferedReader in = new BufferedReader(new FileReader(path))) {
            String str = null;
            Character cc = 0;
            while ((str = in.readLine()) != null) {
                for (int i = 0; i < str.length(); i += 1) {
                    cc = str.charAt(i);
                    map.put(cc, map.getOrDefault(cc, 0) + 1);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

//测试程序
    public static void main(String[] args) {
        HashMap<Character, myArrayList<Character>> table=null;
        HFMcode coder = new HFMcode();
        table=coder.Encoder(coder.pp);
        HashMap<Character, Integer> data_table=coder.Dataprocess(coder.pp);
        System.out.println("HFM编码表:");
        for(Character cc:table.keySet()){
            System.out.print(cc+"-->");
            System.out.print("频数："+data_table.get(cc)+"-->");
            //System.out.println(table.get(cc));
            table.get(cc).show();
        }
    }
}
